/**
 * 访客的IM服务器连接
 *
 * @Date 2021/3/1 16:52
 * @author 周世焕
 */

import config from '@/config'
import {getClientId, getToken} from "@/libs/util";
import {handleMessage} from "@/modules/im/command/handler";
import store from '@/store'

let imServer = process.env.NODE_ENV === 'development' ? config.baseWs.dev : config.baseWs.pro

let imClient = null

let tryConnecting = false

let tryCount = 0

let cleanCountTimer = null

let msgWaitingQueues = []

let msgWaitingTimer = null

let manualClose = false

export const connect = () => {

    manualClose = false

    if(imClient != null) {
        imClient.close()
    }
    if(tryConnecting) {
        return
    }
    tryConnecting = true
    try {
        imClient = new WebSocket(imServer + '/v1/im/'+store.state.tenantId+'/visitor/' + getClientId())
        imClient.onopen = (e) => {
            onOpen()
        }
        imClient.onmessage = (e) => {
            onMessage(e)
        }
        imClient.onerror = (e) => {
            onError(e)
        }
        imClient.onclose = (e) => {
            onClose(e)
        }
    }catch (e) {
        console.log('创建连接失败')
    }
}

export const disconnect = () => {
    manualClose = true
    if(isClientReady()) {
        imClient.close()
        imClient = null
    }
}

function onOpen(){
    store.commit('updateImConnectionState', 1)
    if(cleanCountTimer) {
        clearInterval(cleanCountTimer)
        cleanCountTimer = null
    }else {
        cleanCountTimer = setInterval(function () {
            if(isClientReady()) {
                tryCount--
                if(tryCount == 0) {
                    clearInterval(cleanCountTimer)
                    cleanCountTimer = null
                }
            }
        },3000)
    }
}

function onMessage(e){
    handleMessage(e.data)
}

function onError(e){
    console.log('连接失败')
}

function onClose(e){
    store.commit('updateImConnectionState', 0)
    tryConnecting = false
    if(manualClose) {
        return
    }
    setTimeout(function (){
        tryCount += 1
        console.log('重试，第'+tryCount+'次')
        connect()
    },tryCount * 1000)
}

export const sendMessage = (data) => {
    if(isClientReady()) {
        try {
            imClient.send(data)
            return true
        }catch (e) {
            return false
        }
    }else{
        return false
        // msgWaitingQueues.push(data)
        // loopConsumer()
    }
}

function isClientReady(){
    return imClient!=null && imClient.readyState===1
}

function loopConsumer(){
    if(!isClientReady()) {
        if(msgWaitingTimer!=null) {
            clearTimeout(msgWaitingTimer)
        }
        msgWaitingTimer = setTimeout(function () {
            loopConsumer()
        },1000)
    }else {
        while (msgWaitingQueues.length > 0) {
            sendMessage(msgWaitingQueues.pop())
        }
    }
}
